package netty.io.demo.RPC.utils;

import java.io.*;

/**
 * 表示 共同的工具包
 *
 * @author lihh
 */
public class CommonUtils {
  
  /**
   * 将 Object 转换为 字节
   *
   * @param object 要转换的对象
   * @return 返回的字节
   * @author lihh
   */
  public static byte[] transferBytes(Object object) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
      ObjectOutputStream oout = new ObjectOutputStream(out);
      
      oout.writeObject(object);
      oout.close();
      
      return out.toByteArray();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  
  /**
   * 将 input stream 转换 byte[]
   *
   * @param inputStream 输入流
   * @return 返回字节
   * @author lihh
   */
  public static byte[] inputStream2Bytes(InputStream inputStream) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    
    // 读取InputStream中的数据到字节数组输出流
    byte[] buffer = new byte[1024];
    int length;
    try {
      while ((length = inputStream.read(buffer)) != -1)
        out.write(buffer, 0, length);
    } catch (Exception e) {
      e.printStackTrace();
    }
    
    return out.toByteArray();
  }
  
  /**
   * 将 字节 转换为 对象
   *
   * @param bytes 待转换的字节
   * @return 字节数
   * @author lihh
   */
  public static Object transferObject(byte[] bytes) {
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    try {
      ObjectInputStream inputStream = new ObjectInputStream(byteArrayInputStream);
      
      Object o = inputStream.readObject();
      inputStream.close();
      
      return o;
    } catch (IOException | ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }
}
